package com.example.demo.grbkxt.servlet;

import com.example.demo.grbkxt.mapper.UserMapper;
import com.example.demo.grbkxt.model.User;
import com.example.demo.grbkxt.util.MyBatisUtil;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.*;
import org.apache.ibatis.session.SqlSession;

import java.io.IOException;
import java.util.List;
import java.util.UUID;

@WebServlet("/admin/users/*")
public class AdminUserServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String pathInfo = request.getPathInfo();

        try (SqlSession session = MyBatisUtil.openSession()) {
            UserMapper mapper = session.getMapper(UserMapper.class);

            if (pathInfo == null || pathInfo.equals("/")) {
                List<User> users = mapper.getAllUsers();
                request.setAttribute("users", users);
                request.getRequestDispatcher("/WEB-INF/views/admin/users.jsp").forward(request, response);
            } else if (pathInfo.equals("/edit")) {
                String id = request.getParameter("id");
                System.out.println("Editing user with ID: " + id); // 添加调试日志

                User user = mapper.getUserById(id);
                if (user != null) {
                    System.out.println("Found user: " + user.getUsername()); // 添加调试日志
                    request.setAttribute("user", user);
                    request.getRequestDispatcher("/WEB-INF/views/admin/user-edit.jsp").forward(request, response);
                } else {
                    System.out.println("User not found with ID: " + id); // 添加调试日志
                    response.sendError(HttpServletResponse.SC_NOT_FOUND, "用户不存在");
                }
            }
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String pathInfo = request.getPathInfo();

        try (SqlSession session = MyBatisUtil.openSession()) {
            UserMapper mapper = session.getMapper(UserMapper.class);

            if ("/update".equals(pathInfo)) {
                // 处理更新用户
                String id = request.getParameter("id");
                String username = request.getParameter("username");
                String password = request.getParameter("password");
                boolean isAdmin = "on".equals(request.getParameter("isAdmin"));

                User existingUser = mapper.getUserById(id);
                if (existingUser != null) {
                    existingUser.setUsername(username);
                    if (password != null && !password.trim().isEmpty()) {
                        existingUser.setPassword(password);
                    }
                    existingUser.setAdmin(isAdmin);

                    mapper.updateUser(existingUser);
                    session.commit();
                    response.sendRedirect(request.getContextPath() + "/admin/users");
                } else {
                    response.sendError(HttpServletResponse.SC_NOT_FOUND, "用户不存在");
                }
            } else {
                // 处理添加用户
                String username = request.getParameter("username");
                String password = request.getParameter("password");
                boolean isAdmin = "on".equals(request.getParameter("isAdmin"));

                User user = new User();
                user.setId(UUID.randomUUID().toString());
                user.setUsername(username);
                user.setPassword(password);
                user.setAdmin(isAdmin);

                mapper.addUser(user);
                session.commit();

                response.sendRedirect(request.getContextPath() + "/admin/users");
            }
        }
    }

    @Override
    protected void doDelete(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String id = request.getParameter("id");

        try (SqlSession session = MyBatisUtil.openSession()) {
            UserMapper mapper = session.getMapper(UserMapper.class);
            mapper.deleteUser(id);
            session.commit();
            response.setStatus(200);
        }
    }

    @Override
    protected void doPut(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try (SqlSession session = MyBatisUtil.openSession()) {
            UserMapper mapper = session.getMapper(UserMapper.class);

            String id = request.getParameter("id");
            String username = request.getParameter("username");
            String password = request.getParameter("password");
            boolean isAdmin = "on".equals(request.getParameter("isAdmin"));

            User user = mapper.getUserById(id);
            if (user != null) {
                user.setUsername(username);
                if (password != null && !password.trim().isEmpty()) {
                    user.setPassword(password);
                }
                user.setAdmin(isAdmin);

                mapper.updateUser(user);
                session.commit();
                response.sendRedirect(request.getContextPath() + "/admin/users");
            } else {
                response.sendError(HttpServletResponse.SC_NOT_FOUND, "用户不存在");
            }
        }
    }
}
